package top.guinguo.plugin_05.util;

import com.chenlb.mmseg4j.analysis.MMSegAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.Version;
import org.apache.tika.Tika;
import org.apache.tika.exception.TikaException;
import org.apache.tika.metadata.Metadata;
import org.apache.tika.parser.AutoDetectParser;
import org.apache.tika.parser.ParseContext;
import org.apache.tika.parser.Parser;
import org.apache.tika.sax.BodyContentHandler;
import org.xml.sax.ContentHandler;
import org.xml.sax.SAXException;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;

/**
 * Created by guin_guo on 2017/1/4.
 */
public class IndexUtil {
    public void index() {
        try {
            File file = new File("E:\\test\\lucene\\tika-example\\数据库系统实验教材.pdf");
            Directory directory = FSDirectory.open(new File("E:\\test\\lucene\\tika-files"));
            IndexWriter writer = new IndexWriter(directory, new IndexWriterConfig(Version.LUCENE_35, new MMSegAnalyzer("E:\\test\\lucene\\data")));
            writer.deleteAll();
            Document document = new Document();
            document.add(new Field("content", new Tika().parse(file)));
            writer.addDocument(document);
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public String file2Text(File file) {
        FileInputStream is = null;
        try {
            Parser parser = new AutoDetectParser();
            Metadata metadata = new Metadata();
            metadata.set("guin", "abc");
            metadata.set(Metadata.RESOURCE_NAME_KEY, "beging");
            ParseContext context = new ParseContext();
            context.set(Parser.class, parser);
            ContentHandler handler = new BodyContentHandler();
            is = new FileInputStream(file);
            parser.parse(is, handler, metadata, context);
            for (String s : metadata.names()) {
                System.out.println(s + ": " + metadata.get(s));
            }
            return handler.toString();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (SAXException e) {
            e.printStackTrace();
        } catch (TikaException e) {
            e.printStackTrace();
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }
}
